/*
 * Copyright (c) 2018 maoyan.com
 * All rights reserved.
 *
 */
package com.darren.euc.service.impl;

import com.darren.euc.dao.BannerDao;
import com.darren.euc.entity.Banner;
import com.darren.euc.entity.PageBean;
import com.darren.euc.service.BannerService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 在这里编写类的功能描述
 *
 * @author fangwenhao
 * @created 2018/3/11
 */
@Service
public class BannerServiceImpl implements BannerService {

    @Autowired
    private BannerDao bannerDao;

    @Override
    public PageBean queryForPageBannerHQL(JSONObject data, Integer pageSize, int currentPage) {
        String HQL = " from Banner where 1=1 and status = 1 order by addTime desc";
        return bannerDao.queryForPageByHQL(HQL, pageSize, currentPage);
    }

    @Override
    public Banner aoe(JSONObject data) {
        Long id = data.getLong("id");
        Banner banner = new Banner();
        banner.setId(id);
        banner.setTitle(data.getString("title"));
        banner.setOrderNum(data.getInt("orderNum"));
        banner.setUrl(data.getString("bannerImage"));
        banner.setContentType(data.getInt("contentType"));
        banner.setContent(data.getString("content"));
        banner.setStatus(data.getInt("status"));
        if (id != null && id > 0) {
            banner.setModTime(new Date());
            Banner banner1 = bannerDao.findById(id);
            banner.setAddTime(banner1.getAddTime());
            banner.setPersonName(banner1.getPersonName());
            return bannerDao.merge(banner);
        } else {
            banner.setPersonName(data.getString("personName"));
            banner.setAddTime(new Date());
            banner.setModTime(new Date());
            return bannerDao.save(banner);
        }
    }

    @Override
    public Banner delete(Long id) {
        Banner banner = bannerDao.findById(id);
        if (banner.getStatus() == 1){
            banner.setStatus(0);
        }else if (banner.getStatus() == 0){
            banner.setStatus(1);
        }
        return bannerDao.update(banner);
    }

    @Override
    public List<Map> findAll() {
        String sql = "SELECT b.id, b.title, b.url src, b.content_type type, b.content target " +
                "FROM euc_banner b WHERE b.status=1 ORDER BY order_num desc limit 3";
        List<Map> mapList =  bannerDao.getDataMapList(sql);
        mapList.forEach(x->{//数据处理
            x.put("title", x.get("title"));
            x.put("src",x.get("src"));
            x.put("type", x.get("type"));
            if ( (Long)x.get("type") == 1){
                x.put("target", "/_app/banner_detail?id="+x.get("id"));
            }else {
                x.put("target",x.get("target"));
            }
        });
        return mapList;
    }
}
